using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SunFlower : Enemy
{
     
    // 攻击间隔
    public float attackCd = 2f;
    // 上次被打时间
    float lastOnHitTime;
    // 被打间歇时间
    public float changeTime = 0.1f;
    // 上次使用技能的时间
    private float lastAttackTime;
    // 状态机
    //protected GeneralStates state;
    
    SpriteRenderer[] renderers;

    public Transform sun;

    List<Transform> pos; 
    private void Start()
    {
        canGrab = false;
        // 默认是一个待机的状态
        state = GeneralStates.IDLE;
        onGrab = false;
        renderers = GetComponentsInChildren<SpriteRenderer>();
        pos = new List<Transform>(transform.childCount);
        Debug.Log($"pos{pos}");
        for (int i = 0; i < transform.childCount;i++) {
            pos.Add(transform.GetChild(i));
        }
        
    }


    void Update()
    {
        if (Time.time > lastOnHitTime + changeTime)
        {
            CommonUtils.Instance.SetColor(renderers, Color.white);
        }

        Attack();

    }
    // 攻击
    private void Attack() {
     
        //Debug.Log($"Time.time:{Time.time}, lastAttackTime+cd={lastAttackTime + attackCd} comp:{Time.time< lastAttackTime + attackCd}");
        if (Time.time < lastAttackTime + attackCd)
        {
            return;
        }

        // 发动恐怖的攻击
        Debug.Log("Boss 发动攻击");
        pos = CommonUtils.Instance.ShuffleList(pos);
        int randomMax = new System.Random().Next(pos.Count-1);
        for (int i = 0; i < randomMax;i++) {
            Transform row = pos[i];
            Instantiate(sun, row.position, Quaternion.identity);
        }

        //attackSource.Play();

        lastAttackTime = Time.time;
    }

    

    private void OnCollisionEnter2D(Collision2D collision)
    {
        CommonUtils.Instance.SetColor(renderers, Color.red);
        // 更新受击打时间
        lastOnHitTime = Time.time;
        float diff = 10f;
        if (!SubHp(diff))
        {
            Debug.Log($"死了，状态:{state}");
            // 玩家胜利
            SceneManager.LoadScene(2);
        }
    }
}
